<script lang="ts">
    import { onMount } from 'svelte';
    import { navigate } from 'svelte-routing';
    import { writable } from 'svelte/store';
    import { formatDate } from '../../utils/time';
    import { get, post } from '../../utils/api';
    import { addToast } from '../../stores/toastStore';
    import Header from '../../components/garage/Header.svelte';
    import Modal from '../../components/Modal.svelte';
    import SelectComponent from '../../components/SelectComponent.svelte';

    let loading = true; // 加载中
    let intelligent = ''; // 智能字段
    let modalOpen = false; // 模态框关闭
    let garage_name = ''; // 仓库名称
    let vehicleTypes = []; // 车型
    let garages = []; // 仓库
    const formData = writable({
        // 车辆信息
        plate_number: '鄂AFG2129', // 车牌号
        chassis_number: 'LBGHG52H5F1234567', // 车架号
        type: 1, // 车辆类型
        model: 'SUV', // 车型
        key_present: 1, // 是否有钥匙
        // 入库信息
        garage_id: 1, // 车库
        entry_type: 1, // 入库类型
        entry_at: '2024-09-23 12:00:00', // 入库时间
        driver_name: '张三', // 送车人-姓名
        driver_phone: '17371086562', // 送车人-电话
    });

    let keyPresent;
    formData.subscribe(value => {
        keyPresent = String(value.key_present);
    });

    function intelligentParse() { // 智能-解析
        const lines = intelligent.split('\n');
        const data = {};

        lines.forEach(line => {
            const [key, value] = line.split('：');
            if (key && value) {
                switch (key.trim()) {
                case '库房':
                    garage_name = value.trim();
                    data.garage_id = 1;
                    break;
                case '车牌号':
                    data.plate_number = value.trim();
                    break;
                case '车架号':
                    data.chassis_number = value.trim();
                    break;
                case '车型':
                    data.model = value.trim();
                    break;
                case '有无钥匙':
                    data.key_present = value.trim() === '有' ? 1 : 0;
                    break;
                case '送车时间':
                    data.entry_at = value.trim();
                    break;
                case '送车人':
                    data.driver_name = value.trim();
                    break;
                case '送车人电话':
                    data.driver_phone = value.trim();
                    break;
                default:
                    break;
                }
            }
        });

        formData.set(data);
    }
    function intelligentClear() { // 智能-清空
        intelligent = '';
    }
    function openModal() { // 模态框-打开
        modalOpen = true;
    }
    function closeModal() { // 模态框-关闭
        modalOpen = false;
    }
    function handleSelect(event) { // 库名选择模态框
        $formData.garage_id = event.detail.itemId;
        garage_name = event.detail.itemName;

        closeModal();
    }
    function updateKeyPresent(value) { // 有无钥匙
        formData.update(data => {
            data.key_present = parseInt(value, 10);;

            return data;
        });
    }
    function handleEntryTypeChange() { // 入库类型
        formData.entry_type = parseInt(event.target.value, 10);
    }

    async function fetchVehicleTypes() { // 获取汽车类型
        try {
            const response = await get('/common/categories?type=1');
            vehicleTypes = response.data;
        } catch (error) {
            addToast('车型数据加载失败'+error, 'error', 3000);
        }
    }
    async function getGarages() { // 获取仓库
        try {
            const response = await get('/common/garages');
            garages = response.data;
        } catch (error) {
            addToast('仓库数据加载失败'+error, 'error', 3000);
        }
    }

    const handleSubmit = async () => { // 提交按钮
        const data = $formData;
        data['entry_at'] = formatDate(data['entry_at'])

        try {
            const result = await post('/operation/warehouse-entries', data);

            navigate('/warehouse-entry-result?id='+result.data.id)

            addToast('申请成功', 'info', 3000);
        } catch (error) {
            addToast('提交失败'+error, 'error', 3000);
        }
    };
    onMount(() => {
        fetchVehicleTypes(); // 获取汽车类型

        try {
            getGarages(); // 获取仓库
        } catch (err) {
        } finally {
            loading = false;
        }
    });
</script>

<main>
    <Header title="入库报备" />
    <div class="p-4">
        <div class="bg-blue-50 p-4 rounded-lg border border-gray-200 shadow-sm mb-4">
            <textarea placeholder="库房：黄石库
车牌号：鄂AFG2128
车架号：12344223225
车型：比亚迪 宋Pro DM-i
有无钥匙：有
送车时间：2024-10-05 12:00
送车人：张三丰
送车人电话：17371086562" class="flex w-full h-48 border-none" bind:value={intelligent}></textarea>
            <div class="flex justify-between mt-4">
                <button on:click={intelligentClear} class="bg-white border border-gray-300 text-gray-600 px-4 py-2 rounded shadow-sm">清空</button>
                <button on:click={intelligentParse} class="bg-blue-500 text-white px-4 py-2 rounded shadow-sm">智能识别</button>
            </div>
        </div>

        <div class="bg-white p-4 rounded-lg border border-gray-200 shadow-sm">
            <div class="form-group mb-4">
                <label class="text-gray-600">库房</label>
                <div class="input-field" on:click={openModal}>{garage_name || '点击选择库房'}</div>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">车牌号</label>
                <input type="text" class="input-field" placeholder="请输入车牌号" bind:value={$formData.plate_number}>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">车架号</label>
                <input type="text" class="input-field" placeholder="请输入车架号" bind:value={$formData.chassis_number}>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">车量类型</label>
                <select bind:value={$formData.type} class="input-field">
                    <option value="" disabled>请选择车辆类型</option>
                    {#each vehicleTypes as type}
                        <option value={type.id} selected>{type.name}</option>
                    {/each}
                </select>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">车型</label>
                <input type="text" class="input-field" placeholder="请输入车型" bind:value={$formData.model}>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">车钥匙</label>
                <div class="flex items-center mt-1">
                    <label class="mr-2 items-center">
                        <input type="radio" name="key_present" value="1" bind:group={keyPresent} on:change={() => updateKeyPresent(1)} class="mr-1">有
                    </label>
                    <label class="items-center">
                        <input type="radio" name="key_present" value="0" bind:group={keyPresent} on:change={() => updateKeyPresent(0)} class="mr-1">无
                    </label>
                </div>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">入库方式</label>
                <div class="flex items-center mt-1">
                    <label class="items-center">
                        <input type="radio" name="entry" value="1" on:change={handleEntryTypeChange} checked class="mr-1">普通入库
                    </label>
                </div>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">送车人姓名</label>
                <input type="text" class="input-field" placeholder="请输入送车人姓名" bind:value={$formData.driver_name}>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">送车人电话</label>
                <input type="text" class="input-field" placeholder="请输入送车人电话" bind:value={$formData.driver_phone}>
            </div>
            <div class="form-group mb-4">
                <label class="text-gray-600">送车时间</label>
                <input type="datetime-local" class="input-field" placeholder="请输入送车时间" bind:value={$formData.entry_at}>
            </div>

            <div class="flex justify-end mt-4">
                <button class="bg-blue-500 text-white px-4 py-2 rounded shadow-sm" on:click={handleSubmit}>提交</button>
            </div>
        </div>
        {#if !loading}
            <Modal open={modalOpen} on:close={closeModal}>
                <SelectComponent categories={garages} selectedId={$formData.garage_id} on:select={handleSelect} />
            </Modal>
        {/if}
    </div>
</main>

<style lang="scss">
  .form-group {
    display: flex;
    align-items: center;
    padding-bottom: 1rem;
    border-bottom: 1px solid #e5e7eb;
    &:last-child {
      border-bottom: none;
    }
    label {
      flex: 0 0 100px;
      margin-right: 1rem;
    }
    input, textarea, select {
      flex: 1;
      border: none; // 去除 input 的边框
      padding: 0.5rem; // 添加内边距
      background-color: #f9fafb; // 设置背景颜色
      &:focus {
        outline: none; // 去除 focus 的边框
      }
    }
  }
  .form-group .flex.items-center label {
    margin-right: 2rem;
  }
  .input-area {
    border: 1px solid #ccc;
    padding: 8px;
    cursor: pointer;
  }
</style>
